<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/store/modules/user";
import { useUserNavigation } from "@/hooks/useUserNavigation";
import { searchVideosApi, searchUsersApi } from "@/api/search";
import { formatDate } from "@/utils/day";
import { ElEmpty, ElIcon } from "element-plus";
import { Star } from "@element-plus/icons-vue";
// 首先在文件顶部的import部分添加:
import { useVideoPlayerStore } from "@/store/modules/videoPlayer";

// 在setup函数内添加:
const videoPlayerStore = useVideoPlayerStore();

// 路由
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const { navigateToUserProfile } = useUserNavigation();

// 用户状态
const isLoggedIn = computed(() => userStore.isLoggedIn());
const userAvatar = computed(() => userStore.userInfo?.avatar || "");

// 搜索相关
const searchKeyword = ref("");
const activeTab = ref("videos");
const hasSearched = ref(false);
const videoResults = ref([]);
const userResults = ref([]);

// 添加记录上次搜索关键词的变量
const lastSearchKeyword = ref("");

// 添加记录各标签页是否已加载数据的变量
const videoTabLoaded = ref(false);
const userTabLoaded = ref(false);

// 分页和加载状态
const loading = ref(false);
const isInitialLoading = ref(true);
const videoPage = ref(1);
const userPage = ref(1);
const pageSize = ref(10);
const totalVideoCount = ref(0);
const totalUserCount = ref(0);

// 获取当前登录用户的ID
const currentUserId = computed(() => userStore.userInfo?.id || "");

const noMoreVideos = computed(() => {
  return (
    videoResults.value.length >= totalVideoCount.value &&
    totalVideoCount.value > 0
  );
});

const noMoreUsers = computed(() => {
  return (
    userResults.value.length >= totalUserCount.value && totalUserCount.value > 0
  );
});

// 返回上一页
const goBack = () => {
  router.back();
};

// 打开登录模态框
const openLoginModal = () => {
  userStore.openAuthModal("login");
};

// 跳转到用户个人页
const goToUserProfile = () => {
  router.push("/mine");
};

// 处理用户点击
const handleUserClick = (userId) => {
  if (userId) {
    navigateToUserProfile(userId);
  }
};

// 处理视频作者点击
const handleAuthorClick = (event, authorId) => {
  event.stopPropagation();
  if (authorId) {
    navigateToUserProfile(authorId);
  }
};

// 处理视频卡片点击
const handleVideoClick = (videoId, video) => {
  console.log("点击视频:", videoId);
  // router.push(`/video/${videoId}`);
  // 打开全局视频播放器
  // 打开全局视频播放器
  videoPlayerStore.openVideoModal(videoId, video);
};

// 处理搜索
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) return;

  // 检查搜索关键词是否变化
  const keywordChanged = searchKeyword.value !== lastSearchKeyword.value;

  // 如果关键词变化，重置所有状态
  if (keywordChanged) {
    resetAllSearch();
    lastSearchKeyword.value = searchKeyword.value;
  }

  // 设置搜索状态
  hasSearched.value = true;

  // 根据当前标签页和加载状态决定是否需要加载数据
  if (activeTab.value === "videos") {
    if (keywordChanged || !videoTabLoaded.value) {
      isInitialLoading.value = true;
      await fetchVideoResults(1);
      videoTabLoaded.value = true;
    }
  } else {
    if (keywordChanged || !userTabLoaded.value) {
      isInitialLoading.value = true;
      await fetchUserResults(1);
      userTabLoaded.value = true;
    }
  }
};

// 重置所有搜索状态
const resetAllSearch = () => {
  // 重置视频搜索状态
  videoResults.value = [];
  videoPage.value = 1;
  totalVideoCount.value = 0;
  videoTabLoaded.value = false;

  // 重置用户搜索状态
  userResults.value = [];
  userPage.value = 1;
  totalUserCount.value = 0;
  userTabLoaded.value = false;
};

// 重置当前标签页的搜索状态
const resetSearch = () => {
  if (activeTab.value === "videos") {
    videoResults.value = [];
    videoPage.value = 1;
    totalVideoCount.value = 0;
  } else {
    userResults.value = [];
    userPage.value = 1;
    totalUserCount.value = 0;
  }
};

// 加载视频搜索结果
const fetchVideoResults = async (page) => {
  if (loading.value) return;
  loading.value = true;

  try {
    const params = {
      keyword: searchKeyword.value.trim(),
      page: page,
      limit: pageSize.value,
    };

    const response = await searchVideosApi(params);

    if (response && response.data) {
      const { data } = response;
      const { total } = response.pagination || {};

      totalVideoCount.value = total || 0;

      if (page === 1) {
        videoResults.value = data || [];
      } else {
        videoResults.value = [...videoResults.value, ...(data || [])];
      }

      videoPage.value = page;
    } else {
      if (page === 1) {
        videoResults.value = [];
      }
    }
  } catch (error) {
    console.error("获取视频搜索结果失败:", error);
    if (page === 1) {
      videoResults.value = [];
    }
  } finally {
    loading.value = false;
    isInitialLoading.value = false;
  }
};

// 加载用户搜索结果
const fetchUserResults = async (page) => {
  if (loading.value) return;
  loading.value = true;

  try {
    const params = {
      keyword: searchKeyword.value.trim(),
      page: page,
      limit: pageSize.value,
    };

    const response = await searchUsersApi(params);

    if (response && response.data) {
      const { data } = response;
      const { total } = response.pagination || {};

      totalUserCount.value = total || 0;

      if (page === 1) {
        userResults.value = data || [];
      } else {
        userResults.value = [...userResults.value, ...(data || [])];
      }

      userPage.value = page;
    } else {
      if (page === 1) {
        userResults.value = [];
      }
    }
  } catch (error) {
    console.error("获取用户搜索结果失败:", error);
    if (page === 1) {
      userResults.value = [];
    }
  } finally {
    loading.value = false;
    isInitialLoading.value = false;
  }
};

// 修改切换Tab的逻辑，避免重复加载数据
const handleTabClick = () => {
  if (!hasSearched.value || !searchKeyword.value.trim()) return;

  if (activeTab.value === "videos" && !videoTabLoaded.value) {
    // 如果切换到视频标签页且未加载过数据，则加载视频数据
    isInitialLoading.value = true;
    fetchVideoResults(1).then(() => {
      videoTabLoaded.value = true;
    });
  } else if (activeTab.value === "users" && !userTabLoaded.value) {
    // 如果切换到用户标签页且未加载过数据，则加载用户数据
    isInitialLoading.value = true;
    fetchUserResults(1).then(() => {
      userTabLoaded.value = true;
    });
  }
};

// 处理滚动加载更多
const handleScroll = (event) => {
  const scrollElement = event.target;
  const scrollPosition = scrollElement.scrollTop + scrollElement.clientHeight;
  const scrollHeight = scrollElement.scrollHeight;

  if (
    scrollPosition >= scrollHeight - 100 &&
    !loading.value &&
    hasSearched.value
  ) {
    if (activeTab.value === "videos" && !noMoreVideos.value) {
      fetchVideoResults(videoPage.value + 1);
    } else if (activeTab.value === "users" && !noMoreUsers.value) {
      fetchUserResults(userPage.value + 1);
    }
  }
};

// 切换关注状态
const toggleFollow = (user) => {
  if (!isLoggedIn.value) {
    openLoginModal();
    return;
  }

  user.isFollowing = !user.isFollowing;
  // 实际开发中应调用API更新关注状态
};

// 格式化数字
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + "万";
  }
  return num.toString();
};

// 格式化视频时长
const formatDuration = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
};

// 监听搜索框值变化，当清空时重置状态
watch(searchKeyword, (newValue) => {
  if (!newValue.trim() && lastSearchKeyword.value) {
    hasSearched.value = false;
    resetAllSearch();
    lastSearchKeyword.value = "";
  }
});

// 组件挂载时，如果有URL参数中的搜索关键词，则自动执行搜索
onMounted(() => {
  const keyword = route.query.q;

  if (keyword) {
    searchKeyword.value = keyword;
    lastSearchKeyword.value = keyword; // 设置最后搜索关键词
    handleSearch();
  }
});
</script>

<template>
  <div class="search-page">
    <!-- 头部导航栏 -->
    <header class="search-header">
      <div class="header-left">
        <el-button
          icon="ArrowLeft"
          circle
          @click="goBack"
          text
          class="back-btn"
        ></el-button>
      </div>
      <div class="header-center">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索视频或用户"
          prefix-icon="Search"
          clearable
          @keyup.enter="handleSearch"
          class="search-input"
        >
          <template #append>
            <el-button @click="handleSearch" class="search-btn">搜索</el-button>
          </template>
        </el-input>
      </div>
      <div class="header-right">
        <template v-if="isLoggedIn">
          <el-avatar
            :size="32"
            :src="userAvatar"
            @click="goToUserProfile"
          ></el-avatar>
        </template>
        <template v-else>
          <el-button type="primary" size="small" @click="openLoginModal"
            >登录</el-button
          >
        </template>
      </div>
    </header>

    <!-- 搜索内容区域 -->
    <div class="search-content" @scroll="handleScroll">
      <el-tabs
        v-model="activeTab"
        @tab-click="handleTabClick"
        class="custom-tabs"
      >
        <!-- 视频列表部分 -->
        <el-tab-pane label="视频" name="videos">
          <!-- 初始状态 - 未搜索 -->
          <div v-if="!hasSearched" class="search-placeholder">
            <el-empty description="请输入关键词搜索视频" :image-size="150" />
          </div>

          <!-- 搜索状态 -->
          <div v-else>
            <!-- 加载状态 -->
            <div v-if="isInitialLoading" class="loading-overlay">
              <div class="loading-spinner"></div>
            </div>

            <!-- 内容为空状态 -->
            <div v-else-if="videoResults.length === 0" class="empty-result">
              <el-empty description="没有找到相关视频" :image-size="150" />
            </div>

            <!-- 有内容状态 -->
            <template v-else>
              <div class="video-grid">
                <div
                  v-for="video in videoResults"
                  :key="video.video_id || video.id"
                  class="video-card"
                  @click="handleVideoClick(video.video_id || video.id, video)"
                >
                  <!-- 视频卡片内容保持不变 -->
                  <div class="video-thumbnail">
                    <img
                      :src="video.cover_url || video.coverUrl"
                      alt="视频封面"
                    />
                    <div class="video-duration">
                      {{ formatDuration(video.duration) }}
                    </div>
                    <div class="video-like">
                      <el-icon><star /></el-icon>
                      {{ video.likes_count || 0 }}
                    </div>
                  </div>
                  <div class="video-info">
                    <div class="video-title">{{ video.title }}</div>
                    <div
                      class="video-author"
                      @click.stop="
                        handleAuthorClick(
                          $event,
                          video.user?.id || video.author_id
                        )
                      "
                    >
                      <div style="display: flex; align-items: center">
                        <el-avatar
                          :size="20"
                          :src="
                            video.user?.avatar ||
                            video.author_avatar ||
                            video.authorAvatar
                          "
                        ></el-avatar>
                        <span class="author-name">{{
                          video.user?.username
                        }}</span>
                      </div>
                      <span>{{ formatDate(video.created_at) }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 加载更多或无更多内容 -->
              <div v-if="loading && !isInitialLoading" class="loading-more">
                <div class="loading-spinner-dots">
                  <div></div>
                  <div></div>
                  <div></div>
                </div>
                <span>加载中...</span>
              </div>

              <!-- 没有更多内容提示 -->
              <div v-else-if="noMoreVideos" class="no-more">没有更多视频了</div>
            </template>
          </div>
        </el-tab-pane>

        <!-- 用户列表部分 -->
        <el-tab-pane label="用户" name="users">
          <!-- 初始状态 - 未搜索 -->
          <div v-if="!hasSearched" class="search-placeholder">
            <el-empty description="请输入关键词搜索用户" :image-size="150" />
          </div>

          <!-- 搜索状态 -->
          <div v-else>
            <!-- 加载状态 -->
            <div v-if="isInitialLoading" class="loading-overlay">
              <div class="loading-spinner"></div>
            </div>

            <!-- 内容为空状态 -->
            <div v-else-if="userResults.length === 0" class="empty-result">
              <el-empty description="没有找到相关用户" :image-size="150" />
            </div>

            <!-- 有内容状态 -->
            <template v-else>
              <div class="user-grid">
                <div
                  v-for="user in userResults"
                  :key="user.id || user.user_id"
                  class="user-card"
                >
                  <!-- 用户卡片内容保持不变 -->
                  <div class="user-header">
                    <div
                      class="user-avatar-name"
                      @click="handleUserClick(user.id || user.user_id)"
                    >
                      <div class="user-avatar">
                        <el-avatar :size="48" :src="user.avatar"></el-avatar>
                      </div>
                      <div class="user-name-container">
                        <div class="user-name">
                          {{ user.username || user.name }}
                        </div>
                      </div>
                    </div>
                    <!-- 判断是否为当前用户 -->
                    <template
                      v-if="
                        currentUserId &&
                        (user.id === currentUserId ||
                          user.user_id === currentUserId)
                      "
                    >
                    <el-button type="primary" disabled="">
                        自己
                      </el-button>
                    </template>
                    <template v-else>
                      <el-button type="primary" @click="toggleFollow(user)">
                        {{ user.isFollowing ? "已关注" : "关注" }}
                      </el-button>
                    </template>
                  </div>

                  <div class="user-stats">
                    <div class="stat-item">
                      <div class="stat-label">粉丝：</div>
                      <div class="stat-value">
                        {{ formatNumber(user.following_count || 0) }}
                      </div>
                    </div>
                    <div class="stat-item">
                      <div class="stat-label">作品：</div>
                      <div class="stat-value">
                        {{ formatNumber(user.videos || user.video_count || 0) }}
                      </div>
                    </div>
                  </div>

                  <div class="user-bio">
                    {{ user.bio || "这个人很懒~什么都没有留下。" }}
                  </div>
                </div>
              </div>

              <!-- 加载更多或无更多内容 -->
              <div v-if="loading && !isInitialLoading" class="loading-more">
                <div class="loading-spinner-dots">
                  <div></div>
                  <div></div>
                  <div></div>
                </div>
                <span>加载中...</span>
              </div>

              <!-- 没有更多内容提示 -->
              <div v-else-if="noMoreUsers" class="no-more">没有更多用户了</div>
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped>
.search-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #161823;
  /* 修改为深色背景 */
  color: #fff;
}

.search-header {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  background-color: #1a1c25;
  /* 深色导航栏 */
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.header-left {
  flex: 0 0 40px;
}

.back-btn {
  color: #fff;
  /* 返回按钮颜色 */
}

.header-center {
  flex: 1;
  margin: 0 10px;
  max-width: 500px;
  /* 限制搜索框最大宽度 */
}

.search-input :deep(.el-input__wrapper) {
  background-color: #252836;
  /* 搜索框背景色 */
  box-shadow: none;
  border: 1px solid #363a4f;
}

.search-input :deep(.el-input__inner) {
  color: #fff;
}

.search-input :deep(.el-input__prefix) {
  color: #8a8d98;
}

.search-btn {
  background-color: #1890ff;
  border-color: #1890ff;
  color: #fff;
}

.header-right {
  flex: 0 0 40px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.search-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 96px;
}

/* 自定义tabs样式 */
.custom-tabs :deep(.el-tabs__header) {
  margin-bottom: 24px;
  border-bottom: 1px solid #363a4f;
}

.custom-tabs :deep(.el-tabs__item) {
  color: #8a8d98;
  font-size: 16px;
  padding: 0 0 12px 0;
  margin-right: 24px;
}

.custom-tabs :deep(.el-tabs__item.is-active) {
  color: #1890ff;
  font-weight: bold;
}

.custom-tabs :deep(.el-tabs__active-bar) {
  display: none;
  /* 隐藏底部指示条 */
}

/* 隐藏底部的细线 */
.custom-tabs :deep(.el-tabs__nav-wrap:after) {
  display: none;
}

.search-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  color: #8a8d98;
}

.search-placeholder :deep(.el-empty__description) {
  color: #8a8d98;
}

/* 视频网格样式 */
.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  padding-top: 8px;
}

.video-card {
  background-color: #252836;
  /* 卡片背景色 */
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  transition: transform 0.3s;
}

.video-card:hover {
  transform: translateY(-4px);
}

.video-thumbnail {
  position: relative;
  height: 0;
  padding-bottom: 56.25%;
  /* 16:9比例 */
  overflow: hidden;
}

.video-thumbnail img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 4px;
  border-radius: 4px;
  font-size: 12px;
}

.video-like {
  position: absolute;
  bottom: 8px;
  left: 8px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 4px;
  border-radius: 4px;
  font-size: 12px;
}

.video-info {
  padding: 12px;
}

.video-title {
  font-weight: bold;
  margin-bottom: 8px;
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  color: #fff;
}

.video-author {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  color: #8a8d98;
}

.author-name {
  margin-left: 8px;
}

.video-author span {
}

.video-stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #6c7083;
}

/* 用户网格样式 */
.user-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.user-card {
  background-color: #252836;
  /* 卡片背景色 */
  border-radius: 8px;
  padding: 16px 20px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

/* 上部分：头像、用户名和关注按钮 */
.user-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  justify-content: space-between;
}

.user-avatar-name {
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 12px;
}

.user-name-container {
  flex: 1;
}

.user-name {
  font-weight: bold;
  color: #fff;
  display: flex;
  align-items: center;
  font-size: 16px;
  margin-bottom: 4px;
}

/* 中部分：粉丝和关注数量 */
.user-stats {
  display: flex;
  margin-bottom: 8px;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-value {
  font-size: 12px;
  color: #fff;
}

.stat-label {
  font-size: 12px;
  color: #8a8d98;
}

/* 下部分：用户简介 */
.user-bio {
  font-size: 13px;
  color: #8a8d98;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.empty-result {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
  min-height: 300px;
}

.empty-result :deep(.el-empty__description) {
  color: #8a8d98;
}

/* 滚动条样式 */
.search-content::-webkit-scrollbar {
  width: 6px;
}

.search-content::-webkit-scrollbar-track {
  background: #1a1c25;
}

.search-content::-webkit-scrollbar-thumb {
  background: #363a4f;
  border-radius: 3px;
}

.search-content::-webkit-scrollbar-thumb:hover {
  background: #4a4d61;
}

@media (max-width: 768px) {
  .video-grid,
  .user-grid {
    grid-template-columns: 1fr;
  }

  .header-center {
    max-width: none;
    /* 在移动端取消最大宽度限制 */
  }
}

/* 加载中样式 */
.loading-overlay {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
  width: 100%;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  border-top: 4px solid #1890ff;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.loading-more {
  text-align: center;
  padding: 20px 0;
  color: #8a8d98;
  width: 100%;
}

.loading-spinner-dots {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 8px;
}

.loading-spinner-dots div {
  width: 8px;
  height: 8px;
  margin: 0 4px;
  background-color: #1890ff;
  border-radius: 50%;
  display: inline-block;
  animation: bounceDots 1.4s infinite ease-in-out both;
}

.loading-spinner-dots div:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-spinner-dots div:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounceDots {
  0%,
  80%,
  100% {
    transform: scale(0);
  }

  40% {
    transform: scale(1);
  }
}

.no-more {
  text-align: center;
  padding: 16px 0;
  color: #8a8d98;
  font-size: 13px;
  margin-top: 10px;
}

/* 响应式修改 */
@media (max-width: 1200px) {
  .search-content {
    padding: 16px 48px;
  }

  .video-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
}

@media (min-width: 1600px) {
  .video-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 768px) {
  .search-content {
    padding: 16px 20px;
  }

  .video-grid,
  .user-grid {
    grid-template-columns: 1fr;
  }
}

/* 添加到样式部分 */
.user-name {
  font-weight: bold;
  margin-bottom: 6px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.el-tag {
  font-size: 10px;
  padding: 0 4px;
  margin-left: 4px;
}
</style>
